package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.json.JSONUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.group.GroupBy;
import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.constant.marketing.MerchantCouponTypeEnum;
import com.ssy.lingxi.common.constant.marketing.PlatformCouponTypeEnum;
import com.ssy.lingxi.common.model.bo.MemberAndRoleIdBO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.CollectionPageUtil;
import com.ssy.lingxi.marketing.api.model.request.GiftCouponItemRequest;
import com.ssy.lingxi.marketing.api.model.request.GiftCouponRequest;
import com.ssy.lingxi.marketing.entity.coupon.*;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsDetailBO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsProductBO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsSkuBO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsTagBO;
import com.ssy.lingxi.marketing.model.constant.CanReceiveEnum;
import com.ssy.lingxi.marketing.model.constant.CommonBooleanEnum;
import com.ssy.lingxi.marketing.model.constant.MerchantCouponDetailStatusEnum;
import com.ssy.lingxi.marketing.model.constant.PlatformCouponDetailStatusEnum;
import com.ssy.lingxi.marketing.model.vo.coupon.request.*;
import com.ssy.lingxi.marketing.model.vo.coupon.response.*;
import com.ssy.lingxi.marketing.repository.*;
import com.ssy.lingxi.marketing.service.ICouponReceiveService;
import com.ssy.lingxi.marketing.service.IMobileCouponService;
import com.ssy.lingxi.marketing.service.feign.IPlatformManageFeignService;
import com.ssy.lingxi.marketing.service.feign.IProductFeignService;
import com.ssy.lingxi.marketing.service.feign.ISearchFeignService;
import com.ssy.lingxi.marketing.serviceimpl.component.SuitableMemberInfoComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityCheckRuleComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityGoodsTagAndPriceComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityPriceCalculateComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityQueryComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.coupon.CouponCacheComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.coupon.CouponReceiveCheckRuleComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.coupon.CouponReceiveComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.coupon.CouponUseCheckRuleComponent;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.ShopVO;
import com.ssy.lingxi.search.api.model.request.CommoditySkuRequest;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.CommoditySkuResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * App优惠券服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2021/9/13
 */
@Slf4j
@Service
public class MobileCouponServiceImpl implements IMobileCouponService {

    @Resource
    private MerchantCouponRepository merchantCouponRepository;
    @Resource
    private PlatformCouponRepository platformCouponRepository;
    @Resource
    private MerchantCouponDetailRepository merchantCouponDetailRepository;
    @Resource
    private PlatformCouponDetailRepository platformCouponDetailRepository;
    @Resource
    private CouponReceiveCheckRuleComponent couponReceiveCheckRuleComponent;
    @Resource
    private SuitableMemberInfoComponent suitableMemberInfoComponent;
    @Resource
    private CouponCategoryRepository couponCategoryRepository;
    @Resource
    private CouponBrandRepository couponBrandRepository;
    @Resource
    private CouponGoodsRepository couponGoodsRepository;
    @Resource
    private ICouponReceiveService couponCalculateService;
    @Resource
    private CouponUseCheckRuleComponent couponUseCheckRuleComponent;
    @Resource
    private CouponCacheComponent couponCacheComponent;
    @Resource
    private IProductFeignService productFeignService;
    @Resource
    private ISearchFeignService searchFeignService;
    @Resource
    private ActivityQueryComponent activityQueryComponent;
    @Resource
    private ActivityGoodsTagAndPriceComponent activityGoodsTagAndPriceComponent;
    @Resource
    private CouponReceiveComponent couponReceiveComponent;
    @Resource
    private ActivityCheckRuleComponent activityCheckRuleComponent;
    @Resource
    private ActivityPriceCalculateComponent activityPriceCalculateComponent;
    @Resource
    private JPAQueryFactory queryFactory;
    @Resource
    private IPlatformManageFeignService platformManageFeignService;

    @Override
    public Wrapper<MobileCouponDetailCountResponse> getCouponCount(UserLoginCacheDTO loginUser, MobileCouponDetailCountRequest request) {
        // 返回结果
        MobileCouponDetailCountResponse response = new MobileCouponDetailCountResponse();

        // 未登录返回空
        if (Objects.isNull(loginUser)) {
            response.setReceiveCount(0);
            response.setUserCount(0);
            response.setExpireCount(0);
            return Wrapper.success(response);
        }

        // 平台优惠券
        List<PlatformCouponDetailDO> platformCouponDetailDOList = couponUseCheckRuleComponent.pfReceiveCompleteCouponDetailList(loginUser, request.getEnvironment(),request.getShopId(), null,null);

        // 商家优惠券
        List<MerchantCouponDetailDO> merchantCouponDetailDOList = couponUseCheckRuleComponent.mcReceiveCompleteCouponDetailList(loginUser, request.getEnvironment(), request.getShopId(), request.getMemberId(), request.getRoleId());

        Map<Integer, List<PlatformCouponDetailDO>> platformCouponDetailMap = platformCouponDetailDOList.stream().collect(Collectors.groupingBy(PlatformCouponDetailDO::getStatus));
        Map<Integer, List<MerchantCouponDetailDO>> merchantCouponDetailMap = merchantCouponDetailDOList.stream().collect(Collectors.groupingBy(MerchantCouponDetailDO::getStatus));

        // 已领取数量
        Integer platformReceiveCount = Optional.ofNullable(platformCouponDetailMap.get(PlatformCouponDetailStatusEnum.RECEIVE.getCode())).map(List::size).orElse(0);
        Integer merchantReceiveCount = Optional.ofNullable(merchantCouponDetailMap.get(MerchantCouponDetailStatusEnum.RECEIVE.getCode())).map(List::size).orElse(0);
        response.setReceiveCount(merchantReceiveCount + platformReceiveCount);

        // 已使用数量
        Integer platformUseCount = Optional.ofNullable(platformCouponDetailMap.get(PlatformCouponDetailStatusEnum.USE.getCode())).map(List::size).orElse(0);
        Integer merchantUseCount = Optional.ofNullable(merchantCouponDetailMap.get(MerchantCouponDetailStatusEnum.USE.getCode())).map(List::size).orElse(0);
        response.setUserCount(platformUseCount + merchantUseCount);


        // 已过期数量
        Integer platformExpireCount = Optional.ofNullable(platformCouponDetailMap.get(PlatformCouponDetailStatusEnum.EXPIRE.getCode())).map(List::size).orElse(0);
        Integer merchantExpireCount = Optional.ofNullable(merchantCouponDetailMap.get(MerchantCouponDetailStatusEnum.EXPIRE.getCode())).map(List::size).orElse(0);
        response.setExpireCount(platformExpireCount + merchantExpireCount);

        return Wrapper.success(response);
    }

    private List<MobileCouponDetailResponse> getPfMobileCouponDetailResponseList(UserLoginCacheDTO loginUser,Integer environment, Long shopId, Integer status, Long memberId, Long roleId){
        // 平台优惠券
        List<PlatformCouponDetailDO> platformCouponDetailDOList = couponUseCheckRuleComponent.pfReceiveCompleteByStatusCouponDetailList(loginUser, environment,shopId, status, memberId, roleId);
        return platformCouponDetailDOList.stream().map(e -> {
            MobileCouponDetailResponse response = new MobileCouponDetailResponse();
            response.setId(e.getId());
            response.setCouponId(e.getCoupon().getId());
            response.setBelongType(BelongTypeEnum.PLATFORM.getCode());
            response.setName(e.getCoupon().getName());
            response.setType(e.getCoupon().getType());
            response.setTypeName(MerchantCouponTypeEnum.getCodeMessage(e.getCoupon().getType()));
            response.setDenomination(e.getCoupon().getDenomination());
            response.setUseConditionMoney(e.getCoupon().getUseConditionMoney());
            response.setValidTimeStart(e.getValidTimeStart());
            response.setValidTimeEnd(e.getValidTimeEnd());
            response.setCrateTime(e.getCreateTime());
            response.setCode(e.getCode());
            response.setUseConditionDesc(e.getCoupon().getUseConditionDesc());
            return response;
        }).collect(Collectors.toList());
    }

    private List<MobileCouponDetailResponse> getMerchantMobileCouponDetailResponseList(UserLoginCacheDTO loginUser,Integer environment, Long shopId, Integer status, Long memberId, Long roleId){
        // 商家优惠券
        List<MerchantCouponDetailDO> merchantCouponDetailDOList = couponUseCheckRuleComponent.mcReceiveCompleteByStatusCouponDetailList(loginUser,environment, shopId, status, memberId, roleId);
        return merchantCouponDetailDOList.stream().map(e -> {
            MobileCouponDetailResponse response = new MobileCouponDetailResponse();
            response.setId(e.getId());
            response.setCouponId(e.getCoupon().getId());
            response.setBelongType(BelongTypeEnum.MERCHANT.getCode());
            response.setName(e.getCoupon().getName());
            response.setType(e.getCoupon().getType());
            response.setTypeName(MerchantCouponTypeEnum.getCodeMessage(e.getCoupon().getType()));
            response.setDenomination(e.getCoupon().getDenomination());
            response.setUseConditionMoney(e.getCoupon().getUseConditionMoney());
            response.setValidTimeStart(e.getValidTimeStart());
            response.setValidTimeEnd(e.getValidTimeEnd());
            response.setCrateTime(e.getCreateTime());
            response.setMemberId(e.getMemberId());
            response.setRoleId(e.getRoleId());
            response.setCode(e.getCode());
            response.setUseConditionDesc(e.getCoupon().getUseConditionDesc());
            if (MerchantCouponTypeEnum.COMMON.getCode().equals(e.getCoupon().getType())) {
                // 通用 ignore
            } else if (MerchantCouponTypeEnum.CATEGORY.getCode().equals(e.getCoupon().getType())) {
                // 品类
                List<CouponCategoryDO> couponCategoryDOList = couponCategoryRepository.findAllByCouponId(e.getCoupon().getId());
                response.setCategoryIds(couponCategoryDOList.stream().map(CouponCategoryDO::getCategoryId).collect(Collectors.toList()));
            } else if (MerchantCouponTypeEnum.BRAND.getCode().equals(e.getCoupon().getType())) {
                // 品牌
                List<CouponBrandDO> couponBrandDOList = couponBrandRepository.findAllByCouponId(e.getCoupon().getId());
                response.setBrandIds(couponBrandDOList.stream().map(CouponBrandDO::getBrandId).collect(Collectors.toList()));
            } else if (MerchantCouponTypeEnum.COMMODITY.getCode().equals(e.getCoupon().getType())) {
                // 商品
                List<CouponGoodsDO> couponGoodsDOList = couponGoodsRepository.findAllByBelongTypeAndCouponId(BelongTypeEnum.MERCHANT.getCode(), e.getCoupon().getId());
                response.setProductIds(couponGoodsDOList.stream().map(CouponGoodsDO::getProductId).distinct().collect(Collectors.toList()));
            }
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public Wrapper<PageData<MobileCouponDetailResponse>> pageCouponDetail(UserLoginCacheDTO loginUser, MobileCouponPageRequest request) {
        // 未登录返回空
        if (Objects.isNull(loginUser)) {
            return Wrapper.success(new PageData<>(0L, Collections.emptyList()));
        }

        // 返回结果
        List<MobileCouponDetailResponse> resultList = new ArrayList<>();

        // 平台优惠券
        resultList.addAll(getPfMobileCouponDetailResponseList(loginUser, null,request.getShopId(), request.getStatus(), request.getMemberId(), request.getRoleId()));

        //商家优惠券
        resultList.addAll(getMerchantMobileCouponDetailResponseList(loginUser,null, request.getShopId(), request.getStatus(), request.getMemberId(), request.getRoleId()));

        return Wrapper.success(new PageData<>((long) resultList.size(), CollectionPageUtil.pageList(resultList, request.getCurrent(), request.getPageSize())));
    }


    private List<WebCouponDetailResponse> basePlatformCouponDetailList(UserLoginCacheDTO loginUser,Integer environment, Long shopId, Integer status, Long currentTimeMillis, Long memberId, Long roleId) {
        QCouponShopDO couponShopDO = QCouponShopDO.couponShopDO;
        QPlatformCouponDetailDO platformCouponDetailDO = QPlatformCouponDetailDO.platformCouponDetailDO;

        BooleanBuilder pfPredicates = new BooleanBuilder();
        // 当前会员
        pfPredicates.and(platformCouponDetailDO.subMemberId.eq(loginUser.getMemberId()));
        pfPredicates.and(platformCouponDetailDO.subRoleId.eq(loginUser.getMemberRoleId()));
        // 当前商城是否适用
        if(shopId!=null) {
            pfPredicates.and(couponShopDO.shopId.eq(shopId));
        }
        if(environment!=null){
            pfPredicates.and(couponShopDO.environment.eq(environment));
        }
        // 状态
        if (Objects.nonNull(status)) {
            pfPredicates.and(platformCouponDetailDO.status.eq(status));
        }

        // 有效时间
        if (Objects.nonNull(currentTimeMillis)) {
            pfPredicates.and(platformCouponDetailDO.validTimeStart.loe(currentTimeMillis));
            pfPredicates.and(platformCouponDetailDO.validTimeEnd.goe(currentTimeMillis));
        }

        // 根据店铺筛选
        if (Objects.nonNull(memberId) && Objects.nonNull(roleId)) {
            pfPredicates.and(platformCouponDetailDO.memberId.eq(memberId));
            pfPredicates.and(platformCouponDetailDO.roleId.eq(roleId));
        }

        // 平台优惠券
        JPAQuery<PlatformCouponDetailDO> where = queryFactory.select(platformCouponDetailDO)
                .from(platformCouponDetailDO)
                .leftJoin(couponShopDO).on(platformCouponDetailDO.coupon.id.eq(couponShopDO.couponId).and(couponShopDO.belongType.eq(BelongTypeEnum.PLATFORM.getCode())))
                .where(pfPredicates);
        return new ArrayList<>( where.transform(GroupBy.groupBy(platformCouponDetailDO.id)
                .as(Projections.constructor(WebCouponDetailResponse.class, platformCouponDetailDO.id,ConstantImpl.create(BelongTypeEnum.PLATFORM.getCode()),platformCouponDetailDO.code, platformCouponDetailDO.coupon.id, platformCouponDetailDO.coupon.name, platformCouponDetailDO.coupon.type, platformCouponDetailDO.coupon.denomination, platformCouponDetailDO.coupon.useConditionMoney, platformCouponDetailDO.validTimeStart, platformCouponDetailDO.validTimeEnd, platformCouponDetailDO.createTime, GroupBy.list(Projections.constructor(ShopResponse.class, couponShopDO.shopId))))).values());
    }

    private List<WebCouponDetailResponse> baseMerchantCouponDetailList(UserLoginCacheDTO loginUser,Integer environment, Long shopId, Integer status, Long currentTimeMillis, Long memberId, Long roleId) {
        QCouponShopDO couponShopDO = QCouponShopDO.couponShopDO;
        QMerchantCouponDetailDO merchantCouponDetailDO = QMerchantCouponDetailDO.merchantCouponDetailDO;

        BooleanBuilder pfPredicates = new BooleanBuilder();
        // 当前会员
        pfPredicates.and(merchantCouponDetailDO.subMemberId.eq(loginUser.getMemberId()));
        pfPredicates.and(merchantCouponDetailDO.subRoleId.eq(loginUser.getMemberRoleId()));
        // 当前商城是否适用
        if(shopId!=null) {
            pfPredicates.and(couponShopDO.shopId.eq(shopId));
        }
        if(environment!=null){
            pfPredicates.and(couponShopDO.environment.eq(environment));
        }
        // 状态
        if (Objects.nonNull(status)) {
            pfPredicates.and(merchantCouponDetailDO.status.eq(status));
        }

        // 有效时间
        if (Objects.nonNull(currentTimeMillis)) {
            pfPredicates.and(merchantCouponDetailDO.validTimeStart.loe(currentTimeMillis));
            pfPredicates.and(merchantCouponDetailDO.validTimeEnd.goe(currentTimeMillis));
        }

        // 根据店铺筛选
        if (Objects.nonNull(memberId) && Objects.nonNull(roleId)) {
            pfPredicates.and(merchantCouponDetailDO.memberId.eq(memberId));
            pfPredicates.and(merchantCouponDetailDO.roleId.eq(roleId));
        }

        // 平台优惠券
        JPAQuery<MerchantCouponDetailDO> where = queryFactory.select(merchantCouponDetailDO)
                .from(merchantCouponDetailDO)
                .leftJoin(couponShopDO).on(merchantCouponDetailDO.coupon.id.eq(couponShopDO.couponId).and(couponShopDO.belongType.eq(BelongTypeEnum.MERCHANT.getCode())))
                .where(pfPredicates);
        return new ArrayList<>( where.transform(GroupBy.groupBy(merchantCouponDetailDO.id)
                .as(Projections.constructor(WebCouponDetailResponse.class, merchantCouponDetailDO.id,ConstantImpl.create(BelongTypeEnum.MERCHANT.getCode()),merchantCouponDetailDO.code, merchantCouponDetailDO.coupon.id, merchantCouponDetailDO.coupon.name, merchantCouponDetailDO.coupon.type, merchantCouponDetailDO.coupon.denomination, merchantCouponDetailDO.coupon.useConditionMoney, merchantCouponDetailDO.validTimeStart, merchantCouponDetailDO.validTimeEnd, merchantCouponDetailDO.createTime, GroupBy.list(Projections.constructor(ShopResponse.class, couponShopDO.shopId))))).values());
    }

    @Override
    public Wrapper<PageData<WebCouponDetailResponse>> pageCouponDetailByWeb(UserLoginCacheDTO loginUser, WebCouponPageRequest request) {
        // 未登录返回空
        if (Objects.isNull(loginUser)) {
            return Wrapper.success(new PageData<>(0L, Collections.emptyList()));
        }

        // 返回结果
        List<WebCouponDetailResponse> resultList = new ArrayList<>();

        Set<Long> shopSet =new HashSet<>();
        // 平台优惠券
        List<WebCouponDetailResponse> pfCouponList = basePlatformCouponDetailList(loginUser, request.getEnvironment(), request.getShopId(), request.getStatus(),null, request.getMemberId(), request.getRoleId());
        if(!CollectionUtils.isEmpty(pfCouponList)){
            shopSet.addAll(pfCouponList.stream().flatMap(o -> o.getShopList().stream().map(ShopResponse::getShopId)).collect(Collectors.toSet()));
            resultList.addAll(pfCouponList);
        }


        //商家优惠券
        List<WebCouponDetailResponse> merchantCouponList = baseMerchantCouponDetailList(loginUser, request.getEnvironment(), request.getShopId(), request.getStatus(), null, request.getMemberId(), request.getRoleId());
        if(!CollectionUtils.isEmpty(merchantCouponList)){
            shopSet.addAll(merchantCouponList.stream().flatMap(o -> o.getShopList().stream().map(ShopResponse::getShopId)).collect(Collectors.toSet()));
            resultList.addAll(merchantCouponList);
        }
        //补全商城信息
        if(shopSet.size()>0){
            Map<Long, ShopVO> shopMap = platformManageFeignService.shopMapByIdList(new ArrayList<>(shopSet));
            if(shopMap!=null){
                resultList.forEach(o -> o.getShopList().forEach(k ->{
                    ShopVO shopVO = shopMap.get(k.getShopId());
                    if(shopVO!=null){
                        k.setUrl(shopVO.getUrl());
                        k.setShopName(shopVO.getName());
                    }
                }));
            }
        }
        return Wrapper.success(new PageData<>((long) resultList.size(), CollectionPageUtil.pageList(resultList, request.getCurrent(), request.getPageSize())));
    }

    @Override
    public Wrapper<List<MobileCouponDetailCanUseResponse>> listOrderCouponDetail(UserLoginCacheDTO loginUser, MobileGoodsCartRequest request) {
        // 返回结果
        List<MobileCouponDetailCanUseResponse> resultList = new ArrayList<>();

        // 当前时间
        long currentTimeMillis = System.currentTimeMillis();

        // 店铺的sku商品
        List<MobileGoodsCartRequest.StoreGoods> goodsList = request.getGoodsList();

        // 订单中的商品
        List<Long> skuIdList = goodsList.stream().flatMap(storeGoods -> storeGoods.getSkuIdList().stream()).collect(Collectors.toList());

        // 查询商品sku的活动
        List<ActivityGoodsDetailBO> activityGoodsDetailBOList = activityQueryComponent.selectActivityExecutingGoodsBySku(request.getShopId(), skuIdList,new MemberAndRoleIdBO(loginUser.getMemberId(),loginUser.getMemberRoleId()));
        // 如果有活动, 则校验活动是否可用优惠券
        if (!CollectionUtils.isEmpty(activityGoodsDetailBOList)) {
            Map<Long, List<ActivityGoodsDetailBO>> activityGoodsMap = activityGoodsDetailBOList.stream().collect(Collectors.groupingBy(ActivityGoodsDetailBO::getSkuId));
            for (Map.Entry<Long, List<ActivityGoodsDetailBO>> activityGoodsDetail : activityGoodsMap.entrySet()) {
                // 校验是否可用优惠券
                if (!activityCheckRuleComponent.checkCanUserCoupon(activityGoodsDetail.getValue())) {
                    // 注: 这里会修改goodsList的元素
                    for (MobileGoodsCartRequest.StoreGoods storeGoods : goodsList) {
                        storeGoods.getSkuIdList().removeIf(skuId -> activityGoodsDetail.getKey().equals(skuId));
                    }
                }
            }


        }

        // 平台优惠券
        List<MobileCouponDetailCanUseResponse> platformCouponDetailDOList = couponUseCheckRuleComponent.pfOrderCanUseCouponDetailList(loginUser, request.getShopId(), currentTimeMillis, request.getOrderAmount(), goodsList);
        // 商家优惠券
        List<MobileCouponDetailCanUseResponse> merchantCouponDetailDOList = couponUseCheckRuleComponent.mcOrderCanUseCouponDetailList(loginUser, request.getShopId(), currentTimeMillis, request.getOrderAmount(), goodsList);

        if (skuIdList.size() == 1) {
            this.singleGoodsSelectCouponDetail(platformCouponDetailDOList, merchantCouponDetailDOList);
        } else {
            this.multiGoodsSelectCouponDetail(platformCouponDetailDOList, merchantCouponDetailDOList, skuIdList);
        }

        resultList.addAll(platformCouponDetailDOList);
        resultList.addAll(merchantCouponDetailDOList);

        return Wrapper.success(resultList);
    }

    /**
     * 单商品自动选择优惠券
     * @param platformCouponDetailDOList 平台优惠券
     * @param merchantCouponDetailDOList 商家优惠券
     */
    private void singleGoodsSelectCouponDetail(List<MobileCouponDetailCanUseResponse> platformCouponDetailDOList, List<MobileCouponDetailCanUseResponse> merchantCouponDetailDOList) {
        // 先找平台0元抵扣券
        Optional<MobileCouponDetailCanUseResponse> pfZeroCouponDetailOptional = platformCouponDetailDOList.stream()
                .filter(detail -> PlatformCouponTypeEnum.ZERO_DISCOUNT.getCode().equals(detail.getType()))
                .findFirst();
        if (pfZeroCouponDetailOptional.isPresent()) {
            pfZeroCouponDetailOptional.get().setSelect(CommonBooleanEnum.YES.getCode());
            return;
        }

        // 如果没有平台0元抵扣券, 找商家0元抵扣券
        Optional<MobileCouponDetailCanUseResponse> mcZeroCouponDetailOptional = merchantCouponDetailDOList.stream()
                .filter(detail -> MerchantCouponTypeEnum.ZERO_DISCOUNT.getCode().equals(detail.getType()))
                .findFirst();
        if (mcZeroCouponDetailOptional.isPresent()) {
            mcZeroCouponDetailOptional.get().setSelect(CommonBooleanEnum.YES.getCode());
            return;
        }

        // 最大面额优惠券
        List<MobileCouponDetailCanUseResponse> maxCouponDetailList = new ArrayList<>();

        // 如果没有商家0元抵扣券, 找平台通用优惠券,最大面额
        Optional<MobileCouponDetailCanUseResponse> pfCommonCouponDetailOptional = platformCouponDetailDOList.stream()
                .filter(detail -> PlatformCouponTypeEnum.COMMON.getCode().equals(detail.getType()))
                .max(Comparator.comparing(MobileBaseCouponDetailResponse::getDenomination));
        pfCommonCouponDetailOptional.ifPresent(maxCouponDetailList::add);

        // 如果没有平台通用优惠券, 找商家通用优惠券,最大面额
        Optional<MobileCouponDetailCanUseResponse> mcCommonCouponDetailOptional = merchantCouponDetailDOList.stream()
                .filter(detail -> MerchantCouponTypeEnum.COMMON.getCode().equals(detail.getType()))
                .max(Comparator.comparing(MobileBaseCouponDetailResponse::getDenomination));
        mcCommonCouponDetailOptional.ifPresent(maxCouponDetailList::add);

        // 如果没有商家通用优惠券, 找商家商品券,最大面额
        Optional<MobileCouponDetailCanUseResponse> mcGoodsCouponDetailOptional = merchantCouponDetailDOList.stream()
                .filter(detail -> MerchantCouponTypeEnum.COMMODITY.getCode().equals(detail.getType()))
                .max(Comparator.comparing(MobileBaseCouponDetailResponse::getDenomination));
        mcGoodsCouponDetailOptional.ifPresent(maxCouponDetailList::add);

        // 找出最大的优惠券
        if (!CollectionUtils.isEmpty(maxCouponDetailList)) {
            maxCouponDetailList.stream().max(Comparator.comparing(MobileBaseCouponDetailResponse::getDenomination)).ifPresent(e -> e.setSelect(CommonBooleanEnum.YES.getCode()));
        }
    }

    /**
     * 多商品自动选择优惠券
     * @param platformCouponDetailDOList 平台优惠券
     * @param merchantCouponDetailDOList 商家优惠券
     * @param skuIdList 订单中的商品skuId
     */
    private void multiGoodsSelectCouponDetail(List<MobileCouponDetailCanUseResponse> platformCouponDetailDOList, List<MobileCouponDetailCanUseResponse> merchantCouponDetailDOList, List<Long> skuIdList) {
        // 平台优惠券
        platformCouponDetailDOList.stream()
                .filter(detail -> PlatformCouponTypeEnum.COMMON.getCode().equals(detail.getType()))
                .max(Comparator.comparing(MobileCouponDetailCanUseResponse::getDenomination))
                .ifPresent(detail -> detail.setSelect(CommonBooleanEnum.YES.getCode()));

        // 商家优惠券
        // memberRole - couponDetailList
        Map<MemberAndRoleIdBO, List<MobileCouponDetailCanUseResponse>> memberRoleCouponMap = merchantCouponDetailDOList.stream()
                .collect(Collectors.groupingBy(detail -> new MemberAndRoleIdBO(detail.getMemberId(), detail.getRoleId())));

        // 按店铺商家遍历
        for (Map.Entry<MemberAndRoleIdBO, List<MobileCouponDetailCanUseResponse>> entry : memberRoleCouponMap.entrySet()) {
            // 商家通用优惠券
            List<MobileCouponDetailCanUseResponse> commonCouponDetailList = new ArrayList<>();
            // 商家商品优惠券
            List<MobileCouponDetailCanUseResponse> goodsCouponDetailList = new ArrayList<>();
            // 分类
            for (MobileCouponDetailCanUseResponse mobileCouponDetailCanUseResponse : entry.getValue()) {
                if (MerchantCouponTypeEnum.COMMON.getCode().equals(mobileCouponDetailCanUseResponse.getType())) {
                    commonCouponDetailList.add(mobileCouponDetailCanUseResponse);
                } else if (MerchantCouponTypeEnum.COMMODITY.getCode().equals(mobileCouponDetailCanUseResponse.getType())) {
                    goodsCouponDetailList.add(mobileCouponDetailCanUseResponse);
                }
            }

            // 商家无可用优惠券
            if (CollectionUtils.isEmpty(commonCouponDetailList) && CollectionUtils.isEmpty(goodsCouponDetailList)) {
                continue;
            }

            // 商家最高的通用优惠券
            Optional<MobileCouponDetailCanUseResponse> maxDenominationCommonCouponOptional = commonCouponDetailList.stream()
                    .filter(detail -> MerchantCouponTypeEnum.COMMON.getCode().equals(detail.getType()))
                    .max(Comparator.comparing(MobileBaseCouponDetailResponse::getDenomination));

            // 商家所有商品的优惠券
            List<MobileCouponDetailCanUseResponse> totalDenominationGoodsCouponList = new ArrayList<>();
            // 一个商品只能用一张商品优惠券
            for (Long skuId : skuIdList) {
                Iterator<MobileCouponDetailCanUseResponse> iterator = goodsCouponDetailList.iterator();
                while (iterator.hasNext()) {
                    MobileCouponDetailCanUseResponse next = iterator.next();
                    if (next.getSuitableSkuIdList().stream().anyMatch(suitableSkuId -> suitableSkuId.equals(skuId))) {
                        totalDenominationGoodsCouponList.add(next);
                        iterator.remove();
                    }
                }
            }

            if (maxDenominationCommonCouponOptional.isPresent()) {
                // 有可用的通用优惠券
                // 计算所有商品优惠券的总面额
                BigDecimal totalGoodsDenomination = totalDenominationGoodsCouponList.stream()
                        .map(MobileBaseCouponDetailResponse::getDenomination)
                        .reduce(BigDecimal::add)
                        .orElse(BigDecimal.ZERO);

                // 如果[最高通用优惠券]大于等于[所有商品优惠券]面额,则勾选最高通用优惠券, 否则勾选所有商品优惠券
                if (maxDenominationCommonCouponOptional.get().getDenomination().compareTo(totalGoodsDenomination) >= 0) {
                    maxDenominationCommonCouponOptional.get().setSelect(CommonBooleanEnum.YES.getCode());
                } else {
                    totalDenominationGoodsCouponList.forEach(detail -> detail.setSelect(CommonBooleanEnum.YES.getCode()));
                }
            } else {
                // 无可用的通用优惠券
                totalDenominationGoodsCouponList.forEach(detail -> detail.setSelect(CommonBooleanEnum.YES.getCode()));
            }
        }
    }

    @Override
    public Wrapper<List<MobileCouponResponse>> listShopCoupon(UserLoginCacheDTO loginUser, MobileShopCouponListRequest request) {
        // 返回结果
        List<MobileCouponResponse> resultList = new ArrayList<>();

        // 商家优惠券
        List<MobileCouponResponse> merchantCouponList = new ArrayList<>();
        Wrapper<List<MobileCouponResponse>> merchantCouponWrapper = couponCalculateService.listMerchantCouponCanReceiveComplete(loginUser, request.getShopId(), request.getMemberId(), request.getRoleId());
        if (ResponseCode.SUCCESS.getCode() == merchantCouponWrapper.getCode()) {
            if (!CollectionUtils.isEmpty(merchantCouponWrapper.getData())) {
                merchantCouponList = merchantCouponWrapper.getData();
            }
        }
        resultList.addAll(merchantCouponList);

        return Wrapper.success(resultList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<List<MobileCouponDetailResponse>> autoReceiveCoupon(UserLoginCacheDTO loginUser, AutoReceiveCouponRequest request) {
        // 未登录返回空
        if (Objects.isNull(loginUser)) {
            return Wrapper.success(Collections.emptyList());
        }

        Long shopId = request.getShopId();
        List<BelongTypeCouponRequest> receiveCouponRequestList = request.getCouponList();

        // 根据所属类型分组
        Map<Integer, List<BelongTypeCouponRequest>> receiveCouponMap = receiveCouponRequestList.stream().collect(Collectors.groupingBy(BelongTypeCouponRequest::getBelongType));

        // 返回结果集
        List<MobileCouponDetailResponse> resultList = new ArrayList<>();

        // 平台优惠券
        List<BelongTypeCouponRequest> platformReceiveCouponList = receiveCouponMap.get(BelongTypeEnum.PLATFORM.getCode());
        if (!CollectionUtils.isEmpty(platformReceiveCouponList)) {
            List<Long> ids = platformReceiveCouponList.stream().map(BelongTypeCouponRequest::getCouponId).collect(Collectors.toList());
            Wrapper<List<MobileCouponDetailResponse>> platformCouponWrapper = this.autoReceivePlatformCoupon(loginUser, shopId, ids);
            if (ResponseCode.SUCCESS.getCode() != platformCouponWrapper.getCode()) {
                log.error("领取平台优惠券, errCode: {}, errMsg: {}", platformCouponWrapper.getCode(), platformCouponWrapper.getMessage());
            }
            resultList.addAll(platformCouponWrapper.getData());
        }

        // 商家优惠券
        List<BelongTypeCouponRequest> merchantReceiveCouponList = receiveCouponMap.get(BelongTypeEnum.MERCHANT.getCode());
        if (!CollectionUtils.isEmpty(merchantReceiveCouponList)) {
            List<Long> ids = merchantReceiveCouponList.stream().map(BelongTypeCouponRequest::getCouponId).collect(Collectors.toList());
            Wrapper<List<MobileCouponDetailResponse>> merchantCouponWrapper = this.autoReceiveMerchantCoupon(loginUser, shopId, ids);
            if (ResponseCode.SUCCESS.getCode() != merchantCouponWrapper.getCode()) {
                log.error("领取商家优惠券, errCode: {}, errMsg: {}", merchantCouponWrapper.getCode(), merchantCouponWrapper.getMessage());
            }
            resultList.addAll(merchantCouponWrapper.getData());
        }


        return Wrapper.success(resultList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<ReceiveCouponResponse> receiveCoupon(UserLoginCacheDTO loginUser, ReceiveCouponRequest request) {
        Long shopId = request.getShopId();

        // 返回结果
        ReceiveCouponResponse receiveCouponResponse = new ReceiveCouponResponse();
        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            Wrapper<CanReceiveEnum> platformCouponWrapper = this.receivePlatformCoupon(loginUser, shopId, request.getCouponId());
            if (ResponseCode.SUCCESS.getCode() != platformCouponWrapper.getCode()) {
                return Wrapper.fail(platformCouponWrapper.getCode(), platformCouponWrapper.getMessage());
            }
            receiveCouponResponse.setCanReceive(platformCouponWrapper.getData().getCode());

        } else if (BelongTypeEnum.MERCHANT.getCode().equals(request.getBelongType())) {
            Wrapper<CanReceiveEnum> merchantCouponWrapper = this.receiveMerchantCoupon(loginUser, shopId, request.getCouponId());
            if (ResponseCode.SUCCESS.getCode() != merchantCouponWrapper.getCode()) {
                return Wrapper.fail(merchantCouponWrapper.getCode(), merchantCouponWrapper.getMessage());
            }
            receiveCouponResponse.setCanReceive(merchantCouponWrapper.getData().getCode());

        }

        return Wrapper.success(receiveCouponResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMqMsgReceiveCoupon(GiftCouponRequest request) {
        UserLoginCacheDTO loginUser=new UserLoginCacheDTO();
        loginUser.setMemberId(request.getMemberId());
        loginUser.setMemberRoleId(request.getRoleId());
        loginUser.setCompany(request.getMemberName());
        ReceiveCouponRequest couponRequest=new ReceiveCouponRequest();
        couponRequest.setShopId(request.getShopId());
        for(GiftCouponItemRequest coupon:request.getCouponList()) {
            couponRequest.setCouponId(coupon.getCouponId());
            couponRequest.setBelongType(coupon.getBelongType());
            Wrapper<Void> canReceiveEnumWrapper = receiveMerchantCouponByActivity(loginUser, couponRequest,coupon.getQuantity());
            log.info("赠券结果：coupon:{},result:{},",JSONUtil.toJsonStr(couponRequest), JSONUtil.toJsonStr(canReceiveEnumWrapper));
        }
    }

    @Override
    public Wrapper<List<MobileActivityRelationGoodsResp>> listMerchantCouponRelationGoods(UserLoginCacheDTO loginUser, MobileCouponGoodsRelationReq request) {
        // 非商家优惠券返回空集
        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            return Wrapper.success(Collections.emptyList());
        }

        MerchantCouponDO merchantCouponDO = merchantCouponRepository.findById(request.getCouponId()).orElse(null);
        if (Objects.isNull(merchantCouponDO)) {
            return Wrapper.success(Collections.emptyList());
        }

        // 查询商品信息
        TemplateCommoditySearchRequest templateCommoditySearchRequest = new TemplateCommoditySearchRequest();
        // **没有提供查全部的接口, 所以传分页参数查全部**
        templateCommoditySearchRequest.setCurrent(1);
        templateCommoditySearchRequest.setPageSize(9999);
        if (StringUtils.hasLength(request.getProductName())) {
            templateCommoditySearchRequest.setName(request.getProductName());
        }

        if (MerchantCouponTypeEnum.COMMON.getCode().equals(merchantCouponDO.getType())) {
            templateCommoditySearchRequest.setMemberId(merchantCouponDO.getMemberId());
            templateCommoditySearchRequest.setMemberRoleId(merchantCouponDO.getRoleId());
        } else if (MerchantCouponTypeEnum.COMMODITY.getCode().equals(merchantCouponDO.getType())) {
            List<CouponGoodsDO> couponGoodsDOList = couponGoodsRepository.findAllByBelongTypeAndCouponId(BelongTypeEnum.MERCHANT.getCode(), request.getCouponId());
            if (CollectionUtils.isEmpty(couponGoodsDOList)) {
                return Wrapper.success(Collections.emptyList());
            }

            List<Long> productIds = couponGoodsDOList.stream().map(CouponGoodsDO::getProductId).distinct().collect(Collectors.toList());
            templateCommoditySearchRequest.setIdInList(productIds);
        }
        //只查询现货商品(现货商品才能使用优惠券) 1-现货价格, 2-价格需要询价, 3-积分兑换商品
        templateCommoditySearchRequest.setPriceTypeList(Collections.singletonList(1));
        Wrapper<PageData<CommoditySearchResponse>> pageDataWrapper = productFeignService.searchCommodityList(templateCommoditySearchRequest);
        if (ResponseCode.SUCCESS.getCode() != pageDataWrapper.getCode()) {
            return Wrapper.fail(pageDataWrapper.getCode(), pageDataWrapper.getMessage());
        }

        List<CommoditySearchResponse> templateResponses = Optional.ofNullable(pageDataWrapper.getData().getData()).orElse(new ArrayList<>());

        List<Long> productIds = templateResponses.stream().map(CommoditySearchResponse::getId).collect(Collectors.toList());
        List<ActivityGoodsDetailBO> activityGoodsDetailBOLists = activityQueryComponent.selectMerchantActivityExecutingByProduct(request.getShopId(), productIds);
        // 活动商品标签
        Map<Long, ActivityGoodsProductBO> productTagMap = activityGoodsTagAndPriceComponent.handProductTag(activityGoodsDetailBOLists).stream()
                .collect(Collectors.toMap(ActivityGoodsProductBO::getProductId, e -> e, (e1, e2) -> e2));

        List<MobileActivityRelationGoodsResp> goodsList = new ArrayList<>();
        for (CommoditySearchResponse response : templateResponses) {
            MobileActivityRelationGoodsResp goods = new MobileActivityRelationGoodsResp();
            goods.setProductId(response.getId());
            goods.setMainPic(response.getMainPic());
            goods.setProductName(response.getName());
            goods.setPrice(BigDecimal.valueOf(response.getMin()));
            goods.setUnitName(response.getUnitName());
            goods.setPriceType(response.getPriceType());
            goods.setSlogan(response.getSlogan());
            goods.setSellingPoint(ObjectUtils.isEmpty(response.getSellingPoint()) ? Collections.emptyList() : Arrays.asList(response.getSellingPoint()));
            goods.setMemberId(response.getMemberId());
            goods.setMemberRoleId(response.getMemberRoleId());
            goods.setMemberName(response.getMemberName());
            goods.setStoreId(response.getStoreId());
            goods.setStoreName(response.getStoreName());
            goods.setSold(response.getSold());
            //过滤拼团标签
            List<String> tagList = Optional.ofNullable(productTagMap.get(response.getId())).map(e -> e.getTotalTagList().stream()
                    .filter(o ->!ActivityTypeEnum.GROUP_PURCHASE.getCode().equals(o.getActivityType()))
                    .map(ActivityGoodsTagBO::getActivityTypeTag)
                    .collect(Collectors.toList())).orElse(Collections.emptyList());
            goods.setTagList(tagList);

            goodsList.add(goods);
        }

        return Wrapper.success(goodsList);
    }

    @Override
    public Wrapper<List<MobileActivityRelationGoodsResp>> listMerchantCouponRelationGoodsSku(UserLoginCacheDTO loginUser, MobileCouponGoodsRelationReq request) {
        // 非商家优惠券返回空集
        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            return Wrapper.success(Collections.emptyList());
        }

        MerchantCouponDO merchantCouponDO = merchantCouponRepository.findById(request.getCouponId()).orElse(null);
        if (Objects.isNull(merchantCouponDO)) {
            return Wrapper.success(Collections.emptyList());
        }

        // 查询商品信息
        CommoditySkuRequest templateCommoditySearchRequest = new CommoditySkuRequest();
        templateCommoditySearchRequest.setShopId(request.getShopId());
        templateCommoditySearchRequest.setProvinceCode(request.getProvinceCode());
        templateCommoditySearchRequest.setCityCode(request.getCityCode());
        //已登录显示会员策略价
        if(loginUser!=null){
            templateCommoditySearchRequest.setLoginMemberId(loginUser.getMemberId());
            templateCommoditySearchRequest.setLoginMemberRoleId(loginUser.getMemberRoleId());
        }
        // **没有提供查全部的接口, 所以传分页参数查全部**
        if (StringUtils.hasLength(request.getProductName())) {
            templateCommoditySearchRequest.setName(request.getProductName());
        }

        if (MerchantCouponTypeEnum.COMMON.getCode().equals(merchantCouponDO.getType())) {
            templateCommoditySearchRequest.setMemberId(merchantCouponDO.getMemberId());
            templateCommoditySearchRequest.setMemberRoleId(merchantCouponDO.getRoleId());
        } else if (MerchantCouponTypeEnum.COMMODITY.getCode().equals(merchantCouponDO.getType())) {
            List<CouponGoodsDO> couponGoodsDOList = couponGoodsRepository.findAllByBelongTypeAndCouponId(BelongTypeEnum.MERCHANT.getCode(), request.getCouponId());
            if (CollectionUtils.isEmpty(couponGoodsDOList)) {
                return Wrapper.success(Collections.emptyList());
            }

            List<Long> skuIds = couponGoodsDOList.stream().map(CouponGoodsDO::getSkuId).distinct().collect(Collectors.toList());
            templateCommoditySearchRequest.setSkuIdInList(skuIds);
        }
        Wrapper<List<CommoditySkuResponse>> pageDataWrapper = searchFeignService.getCommoditySkuMap(templateCommoditySearchRequest);
        if (ResponseCode.SUCCESS.getCode() != pageDataWrapper.getCode()) {
            return Wrapper.fail(pageDataWrapper.getCode(), pageDataWrapper.getMessage());
        }

        List<CommoditySkuResponse> templateResponses = Optional.ofNullable(pageDataWrapper.getData()).orElse(new ArrayList<>());

        List<Long> skuIds = templateResponses.stream().map(CommoditySkuResponse::getId).collect(Collectors.toList());
        List<ActivityGoodsDetailBO> activityGoodsDetailBOLists = activityQueryComponent.selectMerchantActivityExecutingBySku(request.getShopId(), skuIds);
        // 活动商品标签
        Map<Long, ActivityGoodsSkuBO> productTagMap = activityGoodsTagAndPriceComponent.handSkuTag(activityGoodsDetailBOLists).stream()
                .collect(Collectors.toMap(ActivityGoodsSkuBO::getSkuId, e -> e, (e1, e2) -> e2));

        List<MobileActivityRelationGoodsResp> goodsList = new ArrayList<>();
        for (CommoditySkuResponse response : templateResponses) {
            MobileActivityRelationGoodsResp goods = new MobileActivityRelationGoodsResp();
            goods.setProductId(response.getCommodityId());
            goods.setSkuId(response.getId());
            goods.setMainPic(response.getMainPic());
            goods.setProductName(response.getName());
            goods.setPrice(BigDecimal.valueOf(response.getMin()));
            goods.setUnitName(response.getUnitName());
            goods.setPriceType(response.getPriceType());
            goods.setSlogan(response.getSlogan());
            goods.setSellingPoint(ObjectUtils.isEmpty(response.getSellingPoint()) ? Collections.emptyList() : Arrays.asList(response.getSellingPoint()));
            goods.setMemberId(response.getMemberId());
            goods.setMemberRoleId(response.getMemberRoleId());
            goods.setMemberName(response.getMemberName());
            goods.setStoreId(response.getStoreId());
            goods.setStoreName(response.getStoreName());
            goods.setSold(response.getSold());
            //过滤拼团标签
            List<String> tagList = Optional.ofNullable(productTagMap.get(response.getId())).map(e -> e.getTagList().stream()
                    .filter(o ->!ActivityTypeEnum.GROUP_PURCHASE.getCode().equals(o.getActivityType()))
                    .map(ActivityGoodsTagBO::getActivityTypeTag)
                    .collect(Collectors.toList())).orElse(Collections.emptyList());
            goods.setTagList(tagList);
            goodsList.add(goods);
        }

        return Wrapper.success(goodsList);
    }

    /**
     * 自动领取平台优惠券
     */
    private Wrapper<List<MobileCouponDetailResponse>> autoReceivePlatformCoupon(UserLoginCacheDTO loginUser, Long shopId, List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Wrapper.success();
        }

        // 查询平台优惠券
        List<PlatformCouponDO> platformCouponDOList = platformCouponRepository.findAllById(ids);

        // 领取优惠券
        List<PlatformCouponDetailDO> saveCouponDetailList = couponReceiveComponent.autoReceivePlatformCoupon(loginUser, shopId, platformCouponDOList);

        // 返回优惠券信息
        List<MobileCouponDetailResponse> receiveCouponDetailList = saveCouponDetailList.stream().map(e -> {
            MobileCouponDetailResponse response = new MobileCouponDetailResponse();
            response.setId(e.getId());
            response.setCrateTime(e.getCreateTime());
            response.setCouponId(e.getId());
            response.setBelongType(BelongTypeEnum.PLATFORM.getCode());
            response.setName(e.getCoupon().getName());
            response.setType(e.getCoupon().getType());
            response.setTypeName(MerchantCouponTypeEnum.getCodeMessage(e.getCoupon().getType()));
            response.setDenomination(e.getCoupon().getDenomination());
            response.setUseConditionMoney(e.getCoupon().getUseConditionMoney());
            response.setValidTimeStart(e.getValidTimeStart());
            response.setValidTimeEnd(e.getValidTimeEnd());
            response.setCrateTime(e.getCreateTime());
            return response;
        }).collect(Collectors.toList());

        return Wrapper.success(receiveCouponDetailList);
    }

    /**
     * 自动领取商家优惠券
     */
    private Wrapper<List<MobileCouponDetailResponse>> autoReceiveMerchantCoupon(UserLoginCacheDTO loginUser, Long shopId, List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Wrapper.success();
        }

        // 查询商家优惠券
        List<MerchantCouponDO> merchantCouponDOList = merchantCouponRepository.findAllById(ids);

        List<MerchantCouponDetailDO> saveCouponDetailList = couponReceiveComponent.autoReceiveMerchantCoupon(loginUser, shopId, merchantCouponDOList);

        // 返回优惠券信息
        List<MobileCouponDetailResponse> receiveCouponDetailList = saveCouponDetailList.stream().map(e -> {
            MobileCouponDetailResponse response = new MobileCouponDetailResponse();
            response.setId(e.getId());
            response.setCrateTime(e.getCreateTime());
            response.setCouponId(e.getCoupon().getId());
            response.setBelongType(BelongTypeEnum.MERCHANT.getCode());
            response.setName(e.getCoupon().getName());
            response.setType(e.getCoupon().getType());
            response.setTypeName(MerchantCouponTypeEnum.getCodeMessage(e.getCoupon().getType()));
            response.setDenomination(e.getCoupon().getDenomination());
            response.setUseConditionMoney(e.getCoupon().getUseConditionMoney());
            response.setValidTimeStart(e.getValidTimeStart());
            response.setValidTimeEnd(e.getValidTimeEnd());
            response.setCrateTime(e.getCreateTime());
            if (MerchantCouponTypeEnum.COMMON.getCode().equals(e.getCoupon().getType())) {
                // 通用 ignore
            } else if (MerchantCouponTypeEnum.CATEGORY.getCode().equals(e.getCoupon().getType())) {
                // 品类
                List<CouponCategoryDO> couponCategoryDOList = couponCategoryRepository.findAllByCouponId(e.getCoupon().getId());
                response.setCategoryIds(couponCategoryDOList.stream().map(CouponCategoryDO::getCategoryId).collect(Collectors.toList()));
            } else if (MerchantCouponTypeEnum.BRAND.getCode().equals(e.getCoupon().getType())) {
                // 品牌
                List<CouponBrandDO> couponBrandDOList = couponBrandRepository.findAllByCouponId(e.getCoupon().getId());
                response.setBrandIds(couponBrandDOList.stream().map(CouponBrandDO::getBrandId).collect(Collectors.toList()));
            } else if (MerchantCouponTypeEnum.COMMODITY.getCode().equals(e.getCoupon().getType())) {
                // 商品
                List<CouponGoodsDO> couponGoodsDOList = couponGoodsRepository.findAllByBelongTypeAndCouponId(BelongTypeEnum.MERCHANT.getCode(), e.getCoupon().getId());
                response.setProductIds(couponGoodsDOList.stream().map(CouponGoodsDO::getProductId).distinct().collect(Collectors.toList()));
            }
            return response;
        }).collect(Collectors.toList());

        return Wrapper.success(receiveCouponDetailList);
    }

    /**
     * 领取平台优惠券
     */
    public Wrapper<CanReceiveEnum> receivePlatformCoupon(UserLoginCacheDTO loginUser, Long shopId, Long id) {
        // 查询平台优惠券
        PlatformCouponDO platformCouponDO = platformCouponRepository.findById(id).orElse(null);
        if (Objects.isNull(platformCouponDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_RECORDS_DONT_EXIST);
        }

        return couponReceiveComponent.receivePlatformCoupon(loginUser, shopId, platformCouponDO);
    }

    /**
     * 领取商家优惠券
     */
    private Wrapper<CanReceiveEnum> receiveMerchantCoupon(UserLoginCacheDTO loginUser, Long shopId, Long id) {
        // 查询商家优惠券
        MerchantCouponDO merchantCouponDO = merchantCouponRepository.findById(id).orElse(null);
        if (Objects.isNull(merchantCouponDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_RECORDS_DONT_EXIST);
        }

        return couponReceiveComponent.receiveMerchantCoupon(loginUser, shopId, merchantCouponDO);
    }


    /**
     * 赠优惠券活动-给用户送券
     */
    public Wrapper<Void> receiveMerchantCouponByActivity(UserLoginCacheDTO loginUser, ReceiveCouponRequest request,Integer quantity) {
        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            return Wrapper.fail(ResponseCode.PARAM_NOT_EXIST);
        }else if(BelongTypeEnum.MERCHANT.getCode().equals(request.getBelongType())) {
            // 查询商家优惠券
            MerchantCouponDO merchantCouponDO = merchantCouponRepository.findById(request.getCouponId()).orElse(null);
            if (Objects.isNull(merchantCouponDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_RECORDS_DONT_EXIST);
            }
            return couponReceiveComponent.receiveMerchantCouponByActivity(loginUser, request.getShopId(), merchantCouponDO,quantity);
        }
        return Wrapper.fail(ResponseCode.PARAM_NOT_EXIST);
    }
}
